from django.shortcuts import render

from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse, HttpResponse
from ...models import *
from ...utils import jwtUtils
from ...utils.jsonSerialize import serialize_models
import time


# 用户详情
def about(request):
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter(id=user_id).first()
    # 序列化数据集对象
    user_obj = serialize_models(user_obj)
    return JsonResponse ({'msg': '获取个人信息成功 ！', 'data': user_obj, 'code': 200})


# 修改信息
def update(request):
    data = request.POST.dict ()
    # 添加修改时间
    data['update_time'] = time.strftime ('%Y-%m-%d %H:%M:%S', time.localtime ())
    data['is_delete'] = '0'
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter (id=user_id)
    user_obj.update(**data)
    return JsonResponse ({'msg': '更新用户信息成功！', 'code': 200})


# 修改密码
def password(request):
    data = request.POST.dict ()
    # 添加修改时间
    data['update_time'] = time.strftime ('%Y-%m-%d %H:%M:%S', time.localtime ())
    data['is_delete'] = '0'
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter (id=user_id)
    user_obj_filter = UserMsg.objects.filter (id=user_id).first()

    # 检测旧密码是否相同
    res = check_password (data['old_password'], user_obj_filter.password)
    if not res:
        return JsonResponse ({'msg': '输入的旧密码错误！请重新输入！', 'code': 403})
    else:
        # 加密新密码
        data['password'] = make_password (data['new_password'], None, 'pbkdf2_sha256')
        del data['old_password']
        del data['new_password']
        user_obj.update(**data)
        return JsonResponse ({'msg': '更新登录密码成功！', 'code': 200})

